#include <stdio.h>
#include "rijndael.h"

#include <QtCore>

int decrypt(QString srcFile, QString dstFile, QString pwd)
{
	unsigned long rk[RKLENGTH(256)];
	unsigned char key[KEYLENGTH(256)];
	uint i;
	int nrounds;

	QByteArray pwdd= QCryptographicHash::hash(pwd.toUtf8(),QCryptographicHash::Md5);
	for (i = 0; i < sizeof(key); i++) key[i] = i<(uint)pwdd.size()?pwdd.at(i):0;

	QFile src(srcFile);
	if(!src.open(QIODevice::ReadOnly)) return 1;
	char pad= 0;
	src.getChar(&pad);

	QFile dst(dstFile);
	if(!dst.open(QIODevice::WriteOnly)){
		src.close();
		return 1;
	}

	nrounds = rijndaelSetupDecrypt(rk, key, 256);
	int rlen =0;
	unsigned char plaintext[16];
	unsigned char ciphertext[16];
	while (1)
	{
		rlen= src.read((char*)ciphertext, 16);
		if (rlen <= 0) break;
		rijndaelDecrypt(rk, nrounds, ciphertext, plaintext);
		if(dst.write((const char*)plaintext,rlen) == -1)
		{
			src.close();
			dst.close();
			qCritical()<<"Can't write to file!";
			return 1;
		}
	}
	dst.resize(src.size()-1-pad);
	src.close();
	dst.close();
	return 0;
}
